package com.block.datapush.special.service.infoType;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.account.service.impl.AccountItemSpecialServiceImpl;
import com.block.common.annotate.ExceptionLog;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.service.ICountCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.form.enums.PushActionTypeEnum;
import com.block.datapush.model.result.ApiPushResult;
import com.block.datapush.special.enums.OrderStatusEnum;
import com.block.datapush.special.factory.ApiPushFactory;
import com.block.datapush.special.service.IDataInfoCommonService;
import com.block.datapush.special.service.ISpecialCostomInfoProfitService;
import com.block.datapush.special.service.ISpecialCostomInfoService;
import com.block.datapush.special.service.ISpecialDataApiInfoService;
import com.block.db.entity.*;
import com.block.risk.service.IRiskHandlerService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDate;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2022-12-03
 */
@Service
public class MerchantApiInfoServiceImpl implements IDataInfoCommonService {

    private static Logger log = LogFactory.getPushLog();

    @Autowired
    ISpecialCostomInfoService specialCostomInfoService;
    @Autowired
    ISpecialCostomInfoProfitService specialCostomInfoProfitService;
    @Autowired
    IRiskHandlerService riskHandlerService;
    @Autowired
    AccountItemSpecialServiceImpl accountItemSpecialService;
    @Autowired
    ICountCommonService countCommonService;
    @Autowired
    TransactionTemplate transactionTemplate;
    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    ISpecialDataApiInfoService specialDataApiInfoService;

    @Override
    @ExceptionLog(key = "#itemInfo.id", bizType = "机构检查推送", bizName = "机构api检查推送")
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ApiPushResult checkUser(SpecialCostomInfo costomInfo, SpecialCostomItemInfo itemInfo, MemberExtInfo memberExtInfo) throws Exception {

        ApiPushResult returnPushResult = new ApiPushResult();
        returnPushResult.setSuccess(false);

        SpecialDataApiInfo dataApiInfo = this.saveRecord(costomInfo, itemInfo, memberExtInfo);

        // 进行api 撞库操作f
        ApiPushResult apiPushResult =
                ApiPushFactory.getService(costomInfo.getFactoryType())
                        .matchUser(String.valueOf(dataApiInfo.getId()), costomInfo, memberExtInfo, null);
        log.info("【机构API撞库】撞库完成【matchResult】{}【infoId】{}【itemId】{}【uid】{}",
                JSON.toJSONString(apiPushResult), costomInfo.getId(), itemInfo.getId(), memberExtInfo.getUid());

        SpecialDataApiInfo updateEntity = new SpecialDataApiInfo();
        updateEntity.setId(dataApiInfo.getId());
        updateEntity.setResultCode(apiPushResult.getCode());
        updateEntity.setResultMsg(apiPushResult.getMessage());
        updateEntity.setResultInfo(apiPushResult.getResult());
        updateEntity.setBizParam(apiPushResult.getBizParam());
        updateEntity.setUuid(apiPushResult.getTid());

        if (apiPushResult.isSuccess()) {
            returnPushResult.setSuccess(true);
            returnPushResult.setOrderNo(String.valueOf(dataApiInfo.getId()));

            updateEntity.setStatus(OrderStatusEnum.WAIT_PUSH.getValue());
        }else{
            updateEntity.setStatus(OrderStatusEnum.CHECK_ERROR.getValue());
            specialCostomInfoProfitService.saveSpecialPushProfitInfo(String.valueOf(costomInfo.getId()), itemInfo.getPriceAmount(), PushActionTypeEnum.CHECK);
        }
        specialDataApiInfoService.updateById(updateEntity);

        return returnPushResult;
    }

    @Override
    public ApiPushResult registerUser(SpecialCostomInfo costomInfo, MemberPushOrderInfo pushOrderInfo, MemberExtInfo memberExtInfo) throws Exception {

        SpecialDataApiInfo dataApiInfo = specialDataApiInfoService.getById(pushOrderInfo.getPushId());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("order_info_id",pushOrderInfo.getId());
        jsonObject.put("uuid",dataApiInfo.getUuid());
        // 进件
        ApiPushResult apiPushResult =
                ApiPushFactory.getService(costomInfo.getFactoryType())
                        .register(String.valueOf(dataApiInfo.getId()), costomInfo, memberExtInfo, jsonObject);
        log.info("【机构API推送】api推送完成【pushResult】{}【infoId】{}【itemId】{}【uid】{}",
                apiPushResult.isSuccess(), costomInfo.getId(), pushOrderInfo.getTaskId(), memberExtInfo.getUid());

        // 更新机构推送收益信息
        if (!apiPushResult.isSuccess()) {
            specialCostomInfoProfitService.saveSpecialPushProfitInfo(String.valueOf(costomInfo.getId()), pushOrderInfo.getPriceAmount(), PushActionTypeEnum.REGISTER);
        } else {
            specialCostomInfoProfitService.saveSpecialPushProfitInfo(String.valueOf(costomInfo.getId()), pushOrderInfo.getPriceAmount(), PushActionTypeEnum.SUCCESS);
        }

        String status = apiPushResult.getStatus();

        // 根据状态判断是否进行结算
        if (StrUtil.equals(status, "SUCCESS")) {
            // 成功结算
            apiPushResult.setSettleFlag(true);
        } else {
            apiPushResult.setSettleFlag(false);
        }

        // 更新记录
        SpecialDataApiInfo updateEntity = new SpecialDataApiInfo();
        updateEntity.setId(dataApiInfo.getId());
        updateEntity.setStatus(status);
        updateEntity.setBizParam(apiPushResult.getBizParam());
        updateEntity.setResultCode(apiPushResult.getCode());
        updateEntity.setResultMsg(apiPushResult.getMessage());
        updateEntity.setResultInfo(apiPushResult.getResult());
        updateEntity.setQueryInfo(apiPushResult.getOutOrderNo());
        boolean updateRes = specialDataApiInfoService.updateById(updateEntity);
        log.info("【机构API推送】更新推送结果【updateRes】{}【infoId】{}【itemId】{}【uid】{}",
                updateRes, costomInfo.getId(), pushOrderInfo.getTaskId(), memberExtInfo.getUid());

        return apiPushResult;
    }

    /**
     * 撞库以及推送流程
     *
     * @param costomInfo
     * @param memberExtInfo
     * @return
     */
    @Override
    @ExceptionLog(key = "#itemInfo.id", bizType = "机构推送", bizName = "机构api推送")
    public ApiPushResult checkAndRegisterUser(SpecialCostomInfo costomInfo, SpecialCostomItemInfo itemInfo, MemberExtInfo memberExtInfo) throws Exception {

        JSONObject jsonObject = new JSONObject();
        ApiPushResult apiPushResult = new ApiPushResult();
        apiPushResult.setSuccess(false);

        SpecialDataApiInfo apiInfo = this.saveRecord(costomInfo, itemInfo, memberExtInfo);
        boolean saveRes = ObjectUtil.isNotEmpty(apiInfo);
        log.info("【机构API推送】新增api推送结果完成【saveRes】{}【infoId】{}【itemId】{}【uid】{}",
                saveRes, costomInfo.getId(), itemInfo.getId(), memberExtInfo.getUid());
        if (!saveRes) {
            apiPushResult.setMessage("新增推送记录失败");
            return apiPushResult;
        }

        apiPushResult.setOrderNo(String.valueOf(apiInfo.getId()));
        jsonObject.put("orderNo", String.valueOf(apiInfo.getId()));
        jsonObject.put("itemExtData", itemInfo.getExtData());


        // 进行api 撞库操作
        ApiPushResult matchResult =
                ApiPushFactory.getService(costomInfo.getFactoryType())
                        .matchUser(String.valueOf(apiInfo.getId()), costomInfo, memberExtInfo, jsonObject);
        log.info("【机构API推送】撞库完成【matchResult】{}【infoId】{}【itemId】{}【uid】{}",
                matchResult, costomInfo.getId(), itemInfo.getId(), memberExtInfo.getUid());
        if (!matchResult.isSuccess()) {
            // 更新推送记录
            SpecialDataApiInfo updateEntity = new SpecialDataApiInfo();
            updateEntity.setId(apiInfo.getId());
            updateEntity.setStatus("CHECK_ERROR");
            updateEntity.setResultCode(matchResult.getCode());
            updateEntity.setResultMsg(matchResult.getMessage());
            updateEntity.setResultInfo(matchResult.getResult());
            boolean updateRes = specialDataApiInfoService.updateById(updateEntity);

            apiPushResult.setMessage("撞库失败");
            specialCostomInfoProfitService.saveSpecialPushProfitInfo(String.valueOf(costomInfo.getId()), itemInfo.getPriceAmount(), PushActionTypeEnum.CHECK);
            return apiPushResult;
        }

        jsonObject.put("uuid",matchResult.getTid());
        jsonObject.put("skip_url",matchResult.getSkipUrl());
        // 进件
        apiPushResult =
                ApiPushFactory.getService(costomInfo.getFactoryType())
                        .register(String.valueOf(apiInfo.getId()), costomInfo, memberExtInfo, jsonObject);
        log.info("【机构API推送】api推送完成【pushResult】{}【infoId】{}【itemId】{}【uid】{}",
                apiPushResult.isSuccess(), costomInfo.getId(), itemInfo.getId(), memberExtInfo.getUid());

        // 更新机构推送收益信息
        if (!apiPushResult.isSuccess()) {
            specialCostomInfoProfitService.saveSpecialPushProfitInfo(String.valueOf(costomInfo.getId()), itemInfo.getPriceAmount(), PushActionTypeEnum.REGISTER);
        } else {
            specialCostomInfoProfitService.saveSpecialPushProfitInfo(String.valueOf(costomInfo.getId()), itemInfo.getPriceAmount(), PushActionTypeEnum.SUCCESS);
        }

        String status = apiPushResult.getStatus();

        // 根据状态判断是否进行结算
        if (StrUtil.equals(status, "SUCCESS")) {
            // 成功结算
            apiPushResult.setSettleFlag(true);
        } else {
            apiPushResult.setSettleFlag(false);
        }

        // 更新记录
        SpecialDataApiInfo updateEntity = new SpecialDataApiInfo();
        updateEntity.setId(apiInfo.getId());
        updateEntity.setStatus(status);
        updateEntity.setBizParam(apiPushResult.getBizParam());
        updateEntity.setResultCode(apiPushResult.getCode());
        updateEntity.setResultMsg(apiPushResult.getMessage());
        updateEntity.setResultInfo(apiPushResult.getResult());
        updateEntity.setQueryInfo(apiPushResult.getOutOrderNo());
        boolean updateRes = specialDataApiInfoService.updateById(updateEntity);
        log.info("【机构API推送】更新推送结果【updateRes】{}【infoId】{}【itemId】{}【uid】{}",
                updateRes, costomInfo.getId(), itemInfo.getId(), memberExtInfo.getUid());

        return apiPushResult;
    }

    private SpecialDataApiInfo saveRecord(SpecialCostomInfo costomInfo, SpecialCostomItemInfo itemInfo, MemberExtInfo memberExtInfo) {

        SpecialDataApiInfo apiInfo = new SpecialDataApiInfo();
        apiInfo.setInfoId(costomInfo.getId());
        apiInfo.setDateInfo(LocalDate.now().toString());
        apiInfo.setItemId(itemInfo.getId());
        apiInfo.setPriceAmount(itemInfo.getPriceAmount());
        apiInfo.setChannelCode(memberExtInfo.getChannelCode());
        apiInfo.setChannelName(memberExtInfo.getChannelName());
        apiInfo.setUid(memberExtInfo.getUid());
        apiInfo.setUsername(memberExtInfo.getUsername());
        apiInfo.setMobile(memberExtInfo.getMobile());
        apiInfo.setStatus(OrderStatusEnum.INIT.getValue());

        boolean save = specialDataApiInfoService.save(apiInfo);
        return apiInfo;
    }

}
